package ex.hql.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import ex.hql.pojo.Employee;
import ex.hql.pojo.MailConstants;
import ex.hql.pojo.MailLog;
import ex.hql.service.IEmployeeService;
import ex.hql.service.IMailLogService;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @program:yeb
 * @author: hql
 * @Time: 2021/9/5  17:06
 * @description: 邮件发送定时任务
 */
@Component
public class MailTask {

    @Autowired
    private IMailLogService mailLogService;

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 邮件发送定时任务，十秒发送一次
     */
    @Scheduled(cron="0/10 * * * * ?")
    public void mailTask(){
        //查询状态为未投递的消息
        List<MailLog> mailLogList = mailLogService.list(new QueryWrapper<MailLog>().eq("status", 0)
                .lt("tryTime", LocalDateTime.now()));

        mailLogList.forEach(mailLog -> {
            //如果重试次数超过三次，更新状态为投递失败
            if(3<=mailLog.getCount()){
                mailLogService.update(new UpdateWrapper<MailLog>().set("status",2).eq("msgId",mailLog.getMsgid()));

            }else {
                //增加投递次数
                mailLogService.update(new UpdateWrapper<MailLog>().set("count",mailLog.getCount()+1)
                        .set("updateTime",LocalDateTime.now()).set("tryTime",LocalDateTime.now().plusMinutes(MailConstants.MSG_TIMEOUT))
                        .eq("msgId",mailLog.getMsgid()));

                //重新发送消息
                Employee employee = employeeService.getEmployee(mailLog.getEid()).get(0);
                rabbitTemplate.convertAndSend(MailConstants.MAIL_EXCHANGE_NAME,MailConstants.MAIL_ROUTING_KEY_NAME,employee,new CorrelationData(mailLog.getMsgid()));
            }
        });
    }
}
